/* eslint-disable no-console */
<template>
    <div>
        <div class="main-head flex-between container-fluid">
            <div class="title">
                <h1>{{ $t('pro.ssp.bidTitle')}}</h1>
            </div>
        </div>
        <div class="content container-fluid">
            <div class="portlet">
                <div class="tools">
                    <a-spin :spinning="bidListInning">
                        <div style="width: 100%; min-height: 20px">
                            <a-card hoverable
                                    size="small"
                                    class="bid-info"
                                    v-for="(item, index) in bidList"
                                    :key="index"
                                    :headStyle="{'padding': '5px 8px'}"
                            >
                                <div slot="title">
                                    {{ item.from }}
                                </div>

                                <a href="#" @click.prevent="getBid(item.from)" slot="extra">{{$t('pro.ssp.look')}}</a>

                                <!--<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IP: &nbsp;&nbsp;&nbsp;{{item.ipAddress}}</p>-->
                                <p>&nbsp;&nbsp;&nbsp;{{$t('pro.Editcampaigns.Status')}}: &nbsp;&nbsp;&nbsp;<span :class="['status-r', {'run': !item.stopped}]"></span></p>
                                <p>{{$t('pro.ssp.ggs')}}: &nbsp;&nbsp;&nbsp;<span class="size-running">{{ item.running && item.running.length }}</span> </p>
                                <template class="ant-card-actions" slot="actions">
                                   <!-- <a-button type="primary" shape="circle" icon="search" size="small" slot="extra"></a-button>-->
                                  <!--  <a-button shape="circle" icon="reload" size="small" slot="extra" @click="refreshBid(item)"></a-button>-->
                                    <a-switch
                                        :checked="!item.stopped"
                                        :loading="tableLoading"
                                        @change="bottomSwitch($event, item.from, index)"
                                    >
                                        <a-icon type="check" slot="checkedChildren" />
                                        <a-icon type="close" slot="unCheckedChildren" />
                                    </a-switch>
                                </template>

                            </a-card>
                        </div>
                    </a-spin>
                </div>
                <h3 v-show="fromName">{{fromName}}</h3>
                <div class="tools" v-if="!empty"></div>
                <div class="table">
                    <a-spin :spinning="tableLoading">
                        <template v-if="empty">
                           <a-empty image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
                                <span slot="description">{{$t('pro.ssp.empty')}}</span>
                            </a-empty>
                        </template>
                        <template v-else>
                            <a-table
                                :rowKey="record => record.from"
                                :pagination="false"
                                :columns="columns"
                                :dataSource="data"
                                :scroll="{ x: 1000 }">
                            </a-table>
                        </template>
                    </a-spin>

                </div>

               <!-- 图表记录 -->
               <div v-if="!tableLoading && !empty && !!selectBidName">
                       <a-row type="flex" class="margin-t-b">
                           <a-col  :md="11" :sm="24" :xs="24"  class="col-chart">
                               <chart
                                       style="width: 100%;height: 100%"
                                       ref="chartCUP"
                                       :options="chartCUP"
                                       :auto-resize="true"
                               ></chart>
                           </a-col>

                           <a-col :md="11" :sm="24" :xs="24" class="col-chart">
                               <chart
                                       style="width: 100%;height: 100%"
                                       ref="chartMEM"
                                       :options="chartMEM"
                                       :auto-resize="true"
                               ></chart>
                           </a-col>
                       </a-row>

                       <!--<a-row type="flex" class="margin-t-b">

                       </a-row>-->

                       <!--<a-row type="flex" class="margin-t-b">
                           <a-col :span="18" class="col-chart">
                               <chart
                                   style="width: 100%;height: 100%"
                                   ref="chartQPS"
                                   :options="chartQPS"
                                   :auto-resize="true"
                               ></chart>
                           </a-col>
                       </a-row>

                       <a-row type="flex" class="margin-t-b">
                           <a-col :span="18" class="col-chart">
                               <chart
                                   style="width: 100%;height: 100%"
                                   ref="chartABT"
                                   :options="chartABT"
                                   :auto-resize="true"
                               ></chart>
                           </a-col>
                       </a-row>-->
                   </div>

            </div>
        </div>
    </div>
</template>

<script>
    import {getAllBidder, getByNameBidder, startBid, stopBid, } from '../../../api/SSP'

    import echarts from 'echarts/lib/echarts'

    const columns = [
      /*  { title: 'Name', dataIndex: 'from'},*/
        { title: 'Total', dataIndex: 'handled', },
        { title: 'Request', dataIndex: 'request',  },
        { title: 'Fraud', dataIndex: 'fraud',  },
        { title: 'Bid', dataIndex: 'bid',  },
        { title: 'Nobid', dataIndex: 'nobid',  },
        { title: 'Win', dataIndex: 'win',  },
        { title: 'Pixel', dataIndex: 'pixel',  },
        { title: 'Click', dataIndex: 'clicks',  },
        { title: 'Errors', dataIndex: 'error',  },
        { title: '%Bid', dataIndex: '_bid',  },
        { title: '%Win', dataIndex: '_win',  },
        { title: '%Pixel', dataIndex: '_pixel',  },
        { title: '%Click', dataIndex: '_clicks',  },
        { title: '%Fraud', dataIndex: '_fraud',  },
        { title: 'Ad Spend', dataIndex: 'adspend',  },
        { title: 'QPS', dataIndex: 'qps',  },
        { title: 'X-time(avg)', dataIndex: 'avgx',  },
    ];
    export default {
        name: "SSP",
        //当某一些静态不经常发生变化的变量可放在 export default外部 这样组件页面切换不重新计算
        data() {
            return {
                fromName: '',
                empty: true,
                tableLoading: false,
                data: [],
                columns,

                chartCUP: null,
                chartMEM: null,
                chartQPS: null,
                chartABT: null,

                interval: null,

                bidList: [],
                bidListInning: false,
                selectBidName: "",
            }
        },
        methods: {
            resize() {
                let chartCUP = this.$refs.chartCUP, chartMEM = this.$refs.chartMEM;
                   /* chartQPS = this.$refs.chartQPS,
                    chartABT = this.$refs.chartABT;*/

                if (chartCUP) {
                    chartCUP.resize();
                }
                if (chartMEM) {
                    chartMEM.resize();
                }
            },

            bidListFun(res, index) {
                let {code, data} = res.data || {};
                if ( code == 200) {
                    this.bidList[index].stopped = data.stopped
                }
            },

            //判断是否开启关闭
            bottomSwitch(faly, name, index) {
                if (faly) {
                    this.selectBidName = name;
                    startBid(this.selectBidName).then(res => {
                        this.bidListFun(res, index)
                    });
                }else {
                    stopBid(name).then(res => {
                        this.bidListFun(res, index)
                    })
                }
            },

            //初始化加载最上面bid详细信息
            initBidNameList() {
                this.bidList = [];
                this.bidListInning = true;
                getAllBidder().then(res => {
                    let {code, data} = res.data || {};
                    if (code === '200') {
                        this.bidList = data || [];
                    }
                }).finally(() => {
                    this.bidListInning = false
                });
            },

            //刷新bid
            refreshBid(name) {
                this.selectBidName = name;

            },

            getBid(name) {
                this.fromName = name
                console.log(Math.round(Math.random() * 1000));

                this.tableLoading = true;
                this.selectBidName = name;

                getByNameBidder(name).then(res => {
                    let {code, data} = res.data || {};
                    if (code == '200' && data) {
                        this.empty = false;
                        this.apiDateFormat(data);

                        //计算图表的数据
                        this.doSparkLines(data.sparklines || "");
                    }
                }).catch((e) => {
                    console.log(e);
                    //this.empty = true
                }).finally(() => {
                    this.tableLoading = false;

                    //执行完毕开始后 定时刷新
                    if (!this.interval) {
                        this.interval = setInterval(() => {
                            let t = this.getCustomBidder(name);
                            /*if (t) {
                                clearInterval(this.interval);
                                this.interval = null;
                            }*/
                        }, 1200);
                    }
                });


            },

            //二次封装 根据名字查询bid 及 图表数据
            getCustomBidder(name) {
                getByNameBidder(name).then(res => {
                    let {code, data} = res.data || {};
                    if (code == '200' && data) {
                        this.apiDateFormat(data);

                        //计算图表的数据
                        this.doSparkLines(data.sparklines || "");
                    }
                }).catch((e) => {
                    console.log(e);
                    //this.empty = true
                });
                return this.empty
            },

            //格式化图表需要的数据
            doSparkLines(sparklines = "") {
                let sp = JSON.parse(sparklines);

                let abt = sp.avgbidtime;
                let cpu = sp.cpu;
                let mem = sp.memUsed;
                let qps = sp.qps;
                let p = mem.split(" ");
                mem = p[0].replace('M', '');
                mem = Number(mem);

                abt = Number(abt);
                cpu = Number(cpu);

                this.chartCUP.xAxis.data.push("value");
                this.chartCUP.series.data.push(cpu);

                this.chartMEM.xAxis.data.push("value");
                this.chartMEM.series.data.push(mem);

               /* this.chartQPS.xAxis.data.push("value");
                this.chartQPS.series.data.push(qps);

                this.chartABT.xAxis.data.push("value");
                this.chartABT.series.data.push(abt);*/

                console.log(this.chartCUP.xAxis.data.length);
                if (this.chartCUP.xAxis.data.length > 310) {
                    this.chartCUP.xAxis.data.shift();
                    this.chartCUP.series.data.shift();

                    this.chartMEM.xAxis.data.shift();
                    this.chartMEM.series.data.shift();

                    /*this.chartQPS.xAxis.data.shift();
                    this.chartQPS.series.data.shift();

                    this.chartABT.xAxis.data.shift();
                    this.chartABT.series.data.shift();*/
                }
            },

            //重组后端接口数据 转为list
            apiDateFormat(data) {
                let { from, error, request, avgx, adspend, pixel, qps, handled, win, bid, nobid, fraud, clicks } = data.status || {};
                //计算百分比 精确到百分位
                let _bid = 0, _win = 0, _pixel = 0, _clicks = 0, _fraud = 0;
                if (handled != 0) {
                    _bid = Math.floor((bid / handled * 100) / 100);
                    _win = Math.floor((win / handled * 100) / 100);
                    _pixel = Math.floor((pixel / handled * 100) / 100);
                    _clicks = Math.floor((clicks / handled * 100) / 100);
                    _fraud = Math.floor((fraud / handled * 100) / 100);
                }
                avgx = Math.floor(avgx / 100);

                this.data.shift();
                this.data.push({from,error,request, avgx, adspend, pixel, qps, handled, win,bid,nobid,fraud,clicks,_bid, _win, _pixel, _clicks, _fraud});
            },

            isEmpty(target) {
                if(!target || typeof(target) !== 'string' ) return false;
                return !(target.trim());
            },
        },
        created () {
            this.initBidNameList()
        },
        mounted () {

            const defaultChart = {
                animation:false,
                title: {
                    text: ''/*,left:"110px"*/
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                        return params[0].data
                    },
                    axisPointer: {
                        animation: false
                    }
                },
                grid: {
                    left: "0%",
                    right: "0%",
                    bottom: "0%",
                    containLabel: false
                },
                xAxis: {
                    show: true,
                    type: 'category',
                    boundaryGap: true,
                    data: ["value","value","value","value","value","value","value","value"]
                },
                yAxis: {
                    show: true,
                    type: 'value',
                    lineStyle:{
                        color: "#1DA57A",
                    },
                },
                series: {
                    //symbol:"emptyCircle", //去掉小圆点
                    type: 'line',
                    symbol:"emptyCircle",
                    symbolSize:2,

                    areaStyle:{
                        color:"#F1F1F1",
                    },
                    data: [],
                    /*smooth:true,//显示为平滑的曲线*/
                }
            }

            this.chartCUP = JSON.parse(JSON.stringify(defaultChart));
            this.chartMEM = JSON.parse(JSON.stringify(defaultChart));
            this.chartQPS = JSON.parse(JSON.stringify(defaultChart));
            this.chartABT = JSON.parse(JSON.stringify(defaultChart));

            this.chartCUP.title.text = '（CPU）';
            this.chartMEM.title.text = '（MEM）';
            this.chartQPS.title.text = '（QPS）';
            this.chartABT.title.text = '（ABT）';

            this.$nextTick(() => {
              window.addEventListener("resize", this.resize);
            })
        },

        destroyed() {
            window.removeEventListener("resize", this.resize);
            clearInterval(this.interval);
        }
    }
</script>

<style scoped lang="less">
    .col-chart {
        height: 150px;
        border: 1px solid #ccc;
        border-radius: 6px;
        margin: 0 10px 20px 10px ;

    }
    .status-r {
        display: inline-block;
        width: 10px;
        height: 10px;
        background: #FF0000;
        border-radius: 50%;
    }
    .status-r.run {
        background: seagreen;
    }
    .bid-info {
        display: inline-block;
        width: 250px;
        margin-right: 28px;
        margin-top: 20px;
        .ant-card-extra {
            padding: 12px 0!important;
        }
        .ant-card-body p{
           margin-bottom: 8px;
        }
        ul.ant-card-actions {
            background: #eb2f96;
        }
    }
    .size-running {
        width: 20px;
        height: 20px;
        background: #1DA57A;
        border-radius: 50%;
        color: #fff;
        text-align: center;
        display: inline-block;
    }

    .margin-t-b {
        margin: 40px 0
    }


</style>
